package com.xuecheng.media.service.impl;

import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.commons.constants.CommonConstants;
import com.xuecheng.commons.constants.MediaConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.MediaDto;
import com.xuecheng.commons.model.dto.MediaQueryDto;
import com.xuecheng.commons.model.dto.PageRequest;
import com.xuecheng.commons.model.dto.VodUploadDto;
import com.xuecheng.commons.model.vo.MediaVo;
import com.xuecheng.commons.model.vo.PageResponseResult;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.model.vo.VodUploadVo;
import com.xuecheng.commons.utils.BeanHelper;
import com.xuecheng.media.config.VodTemplate;
import com.xuecheng.media.domain.Media;
import com.xuecheng.media.mappers.MediaMapper;
import com.xuecheng.media.service.MediaService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exceptions.BusinessException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 媒资信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-19
 */
@Service
public class MediaServiceImpl extends ServiceImpl<MediaMapper, Media> implements MediaService {

    @Autowired
    private VodTemplate vodTemplate;
    @Override
    public ResponseResult vodToken(VodUploadDto dto) throws Exception {
        String title = dto.getTitle();
        String fileName = dto.getFileName();
        if (StringUtils.isEmpty(title) || StringUtils.isEmpty(fileName)){
            throw new BusinessException(ErrorCode.PARAMSERROR);
        }
        CreateUploadVideoResponse response = vodTemplate.createUploadVideo(title, fileName);
        VodUploadVo vo = new VodUploadVo();
        vo.setRequestId(response.getRequestId());
        vo.setUploadAddress(response.getUploadAddress());
        vo.setUploadAuth(response.getUploadAuth());
        vo.setVideoId(response.getVideoId());
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult refreshVodToken(String videoId) throws Exception {
        RefreshUploadVideoResponse response = vodTemplate.refreshUploadVideo(videoId);

        VodUploadVo vo = new VodUploadVo();
        vo.setRequestId(response.getRequestId());
        vo.setUploadAddress(response.getUploadAddress());
        vo.setUploadAuth(response.getUploadAuth());
        vo.setVideoId(response.getVideoId());
        return ResponseResult.okResult(vo);
    }

    @Override
    public ResponseResult saveMedia(MediaDto dto) throws Exception {
        Media media = BeanHelper.copyProperties(dto, Media.class);

        media.setStatus(CommonConstants.USING_FLAG.toString());
        media.setAuditStatus(MediaConstants.AUDIT_UNPAST_STATUS);
        media.setCreateDate(new Date());
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(dto.getFileId());
        GetPlayInfoResponse.PlayInfo playInfo = response.getPlayInfoList().get(0);
        media.setUrl(playInfo.getPlayURL());
        media.setTimelength(playInfo.getDuration());
        boolean save = this.save(media);
        if (!save) {
            throw new BusinessException(ErrorCode.ADDEERROR);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findByList(PageRequest pageRequest, MediaQueryDto dto) {
        String filename = dto.getFilename();
        String auditStatus = dto.getAuditStatus();
        String type = dto.getType();
        LambdaQueryWrapper<Media> qw = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(filename)) {
            qw.like(Media::getFilename,filename);
        }
        if (StringUtils.isNotBlank(auditStatus)) {
            qw.eq(Media::getAuditStatus,auditStatus);
        }
        if (StringUtils.isNotBlank(type)) {
            qw.eq(Media::getType,type);
        }
        IPage<Media> page=new Page<>(pageRequest.getPageNo(),pageRequest.getPageSize());
        IPage<Media> pageParam = this.page(page, qw);
        List<MediaVo> mediaVos = BeanHelper.copyWithCollection(pageParam.getRecords(), MediaVo.class);
        return PageResponseResult.okResult(pageParam.getTotal(),mediaVos);
    }

    @Override
    public ResponseResult preview(Long mediaId) throws Exception {
        Media media = this.getById(mediaId);
        String fileId = media.getFileId();
        GetPlayInfoResponse response = vodTemplate.getPlayInfo(fileId);
        GetPlayInfoResponse.PlayInfo playInfo = response.getPlayInfoList().get(0);
        media.setUrl(playInfo.getPlayURL());
        return ResponseResult.okResult(playInfo.getPlayURL());
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteMedia(Long mediaId) throws Exception {
        Media media = this.getById(mediaId);
        String fileId = media.getFileId();
        vodTemplate.deleteVideo(fileId);
        this.removeById(mediaId);
        return ResponseResult.okResult();
    }
}
